import wx from 'weixin-js-sdk'

export default {
  namespaced: true,

  state: {
    cityList: null,   // 城市列表
    location: null,   // 定位坐标对象
    selected: localStorage.getItem('selectedCityId')
  },

  mutations: {
    // 写状态
    write (state, payload){
      var key = Object.keys(payload)[0],
      value = Object.values(payload)[0]
      state[key] = value
      key === 'selected' && localStorage.setItem('selectedCityId', value)
    },

    // 回退城市，上一次使用的有效城市 > 默认城市
    fullbackCity (state){
      var selectedCity = localStorage.getItem('selectedCity')
      state.selected = selectedCity || state.cityList.filter(city => city.is_default)[0].id
      localStorage.setItem('selectedCityId', state.selected)
    }
  },

  getters: {
    // 判断当前城市是否支持服务
    hasService: state => cityName => state.cityList.map(city => city.name).includes(cityName.replace(/市$/, '')),

    //获取当前城市的对象
    local (state){
      return state.cityList ? state.cityList.filter(city => city.id === state.selected)[0] : null
    }
  },

  actions: {
    // 获取城市列表，设置cityList
    getCityList (store){
      if(store.state.cityList) return Promise.resolve(store.state.cityList)
      return _api('city/getListByCon').then(data => store.commit('write', { cityList: data }))
    },

    // 设置location
    getLocation (store){
      var {state} = store
      return new Promise((resolve, reject) =>{
        if(state.location){
          resolve(store.getters['local'])
          return
        }        

        _api('wechat/config', 
          { ...(navigator.userAgent.indexOf('iPhone') > -1 ? {} : { url: location.href }) }
        ).then(config =>{
          wx.config(config)
          wx.ready(() => wx.getLocation({
            success (data){
              var location = {
                lat: data.latitude,
                lon: data.longitude
              }
  
              store.commit('write', { location })
  
              _api('common/locationToAddress', location)
              .then(data =>{
                // 返回状态
                var echo = { type: null }

                // 无服务城市
                if(!state.cityList.map(val => val.tx_code).includes(data.city_code)){
                  echo.type = 'noServices'
                  store.commit('fullbackCity')
                  resolve({ type: 'fullback', city: store.getters['local'] })
                  return
                }


                var cityListId = state.cityList.filter(val => val.tx_code === data.city_code)[0].id

                // 城市已改变
                if(state.selected && (state.selected != cityListId)) echo.type = 'changed'
                store.commit('write', { selected: cityListId })

                echo.city = store.getters['local']
                resolve(echo)

              }).catch(reject)
            },

            fail (){
              // 定位失败，执行回退
              store.commit('fullbackCity')
              resolve({ type: 'fullback', city: store.getters['local'] })
            }
          }))

          wx.error(() =>{
            store.commit('fullbackCity')
            resolve({ type: 'fullback', city: store.getters['local'] })
          })
        })
      }).catch(e => console.log(e))
    }
  }
}